using System;
using JetBrains.Annotations;
using UnityEngine;

namespace Locomotion
{
    public class GroundDetector : MonoBehaviour
    {
        public readonly struct GroundChangedEventArgs
        {
            public GroundDetector GroundDetector { get; }
            public Collider2D LandedCollider { get; }
            
            
            public GroundChangedEventArgs(GroundDetector groundDetector, Collider2D landedCollider)
            {
                GroundDetector = groundDetector;
                LandedCollider = landedCollider;
            }
        }
        
        public static event Action<GroundChangedEventArgs> AnyCharacterGroundedChanged;
        
        [SerializeField] private float checkGroundRadius = 0.1f;
        [SerializeField] private LayerMask groundLayer;

        public bool IsGrounded { get; private set; }

        
        void Update()
        {
            Collider2D landedCollider2D = CheckGrounded();
            bool isGrounded = landedCollider2D != null && landedCollider2D.enabled;
            // if (landedCollider2D != null)
            // {
            //     Debug.Log(landedCollider2D.name, landedCollider2D);
            // }
            
            if (IsGrounded != isGrounded)
            {
                IsGrounded = isGrounded;
                AnyCharacterGroundedChanged?.Invoke(new GroundChangedEventArgs(this, landedCollider2D));
            }
        }

        private void OnDrawGizmosSelected()
        {
            Gizmos.DrawWireSphere(transform.position, checkGroundRadius);
        }

        private Collider2D CheckGrounded()
        {
            return Physics2D.OverlapCircle(transform.position, checkGroundRadius, groundLayer);
        }
    }
}
